<script setup lang='ts'>
import type { IAdd, IEdit, IList } from '@fl/api/joint-api/model/service-model'
import type { VxeGridInstance, VxeGridProps, VxePagerEvents } from 'vxe-table'

// serviceDelete
import { serviceAdd, serviceEdit, serviceList } from '@fl/api/joint-api/index'
// import { useMessage } from '@fl/hooks/web/use-message'

import EditForm from './edit-form.vue'
import { useAreaData } from '@/hooks/useAreaList'

// const { createConfirmModal } = useMessage()

const formTypeEunm = {
    add: '新建',
    // destroy: '删除',
    edit: '编辑',
} as const

type RowVO = {
    code: string
    createTime: string
    licence: string
    name: string
    protocol: string
}
const centerDialogVisible = ref(false)
const formType = ref('')
const submitLoading = ref(false)
const dialogTitle = computed(() => {
    return `${formType.value}金融机构`
})
const state = ref({
    code: '',
    enterpriseObjectID: '',
    id: '',
    isDeleted: 0,
    licence: '',
    logo: '',
    name: '',
    protocol: '',
    cityCode: '',
    status: 1,
})
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const { areaList } = useAreaData()

const xGrid = ref<VxeGridInstance<RowVO>>()
const gridOptions = reactive<VxeGridProps<RowVO>>({
    align: 'center',
    columnConfig: {
        resizable: true,
    },
    columns: [
        { title: '序号', type: 'seq', width: 50 },
        { field: 'name', title: '机构名称' },
        { field: 'code', title: '机构编码' },
        { field: 'createTime', title: '创建时间' },
        { field: 'protocol', slots: { default: 'protocol' }, title: '合同' },
        { field: 'licence', slots: { default: 'licence' }, title: '许可证' },
        { slots: { default: 'operate' }, title: '操作', width: 200 },

    ],
    data: [],
    editConfig: {
        mode: 'row',
        showStatus: true,
        trigger: 'manual',
    },
    height: 530,
    keepSource: true,
    loading: false,
    showOverflow: true,
})
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
    findList()
}
async function findList() {
    gridOptions.loading = true
    try {
        const params: IList = {
            page: tablePage.currentPage,
            size: tablePage.pageSize,
            sort: 'create_time,desc',
        }
        const res = await serviceList(params)
        console.log('🚀 ~ findList ~ res:', res)

        if (res.code === 200) {
            gridOptions.loading = false
            gridOptions.data = res.data.records
            tablePage.total = res.data.total
        }
        else {
            gridOptions.loading = false
        }
    }
    catch (error) {
        gridOptions.loading = false
    }
}
findList()
function resetFormParams() {
    submitLoading.value = false
    state.value = {
        code: '',
        enterpriseObjectID: '',
        id: '',
        isDeleted: 0,
        licence: '',
        logo: '',
        name: '',
        protocol: '',
        cityCode: '',
        areaCode: '',
        status: 1,
    }
}
function showForm(type: string, row?: any) {
    formType.value = type
    if (formType.value === formTypeEunm.edit) {
        state.value = {
            code: row.code,
            enterpriseObjectID: row.enterpriseObjectID,
            id: row.id,
            isDeleted: row.isDeleted,
            licence: row.licence,
            logo: row.logo,
            name: row.name,
            protocol: row.protocol,
            cityCode: row?.cityCode ? `${row?.cityCode}-${row?.cityName || ''}` : '',
            areaCode: row?.areaCode ? `${row?.areaCode}-${row?.areaName || ''}` : '',
            status: row.status,
        }
    }
    centerDialogVisible.value = true
}
function preview(row: any, type: string) {
    try {
        const result = JSON.parse(row[type])
        if (result?.fileUrl)
            window.open(result?.fileUrl, '_blank')

        else
            ElMessage.error('暂无数据')
    }
    catch (error) {
        ElMessage.error('暂无数据')
    }
}
function formSubmit() {
    if (formType.value === formTypeEunm.add)
        addData()
    if (formType.value === formTypeEunm.edit)
        editData()
}
async function addData() {
    submitLoading.value = true
    try {
        const options: IAdd = {
            code: state.value.code,
            enterpriseObjectID: state.value.enterpriseObjectID,
            isDeleted: 0,
            licence: state.value.licence,
            logo: state.value.logo,
            name: state.value.name,
            protocol: state.value.protocol,
            status: 1,
            cityCode: state.value.cityCode?.split('-')[0] || '',
            cityName: state.value.cityCode?.split('-')[1] || '',
            areaCode: state.value.areaCode?.split('-')[0] || '',
            areaName: state.value.areaCode?.split('-')[1] || '',
        }
        const res = await serviceAdd(options)
        if (res.code === 200) {
            ElMessage.success('添加成功')
            centerDialogVisible.value = false
            findList()
        }
        else {
            ElMessage.error(res?.msg)
            submitLoading.value = false
        }
    }
    catch (error) {
        submitLoading.value = false
    }
}
async function editData() {
    submitLoading.value = true
    try {
        const options: IEdit = {
            code: state.value.code,
            enterpriseObjectID: String(state.value.enterpriseObjectID),
            id: state.value.id,
            isDeleted: 0,
            licence: state.value.licence,
            logo: state.value.logo,
            name: state.value.name,
            protocol: state.value.protocol,
            status: 1,
             cityCode: state.value.cityCode?.split('-')[0] || '',
            cityName: state.value.cityCode?.split('-')[1] || '',
            areaCode: state.value.areaCode?.split('-')[0] || '',
            areaName: state.value.areaCode?.split('-')[1] || '',
        }
        const res = await serviceEdit(options)
        if (res.code === 200) {
            ElMessage.success('修改成功')
            centerDialogVisible.value = false
            findList()
        }
        else {
            ElMessage.error(res?.msg)
            submitLoading.value = false
        }
    }
    catch (error) {
        submitLoading.value = false
    }
}
// async function deleteRow(row: any) {
//     console.log(row)
//     createConfirmModal({ content: '是否确认删除？', onError: () => {
//         console.log('操作取消！')
//     }, onSuccess: () => {
//         try {
//             serviceDelete(row.id).then((res) => {
//                 if (res.code === 200)
//                     ElMessage.success('删除成功')
//                 findList()
//             })
//         }
//         catch (error) {

//         }
//     } })
// }
function updateloading(val: boolean) {
    submitLoading.value = val
}
</script>

<template>
    <div class="p-30 bg-white">
        <div class="mb-20">
            <ElButton type="primary"
                      @click="showForm(formTypeEunm.add)"
            >
                {{ formTypeEunm.add }}
            </ElButton>
        </div>

        <vxe-grid ref="xGrid"
                  v-bind="gridOptions"
                  :seq-config="{ startIndex: (tablePage.currentPage - 1) * tablePage.pageSize }"
        >
            <template #licence="{ row }">
                <span class="cursor-pointer"
                      style=" color: var(--el-color-primary);"
                      @click="preview(row, 'licence')"
                >
                    查看
                </span>
            </template>

            <template #protocol="{ row }">
                <span class="cursor-pointer"
                      style=" color: var(--el-color-primary);"
                      @click="preview(row, 'protocol')"
                >
                    查看
                </span>
            </template>

            <template #operate="{ row }">
                <ElButton @click="showForm(formTypeEunm.edit, row)">
                    {{ formTypeEunm.edit }}
                </ElButton>

                <!-- <ElButton @click="deleteRow(row)">
                    {{ formTypeEunm.destroy }}
                </ElButton> -->
            </template>

            <template #pager>
                <vxe-pager v-model:current-page="tablePage.currentPage"
                           v-model:page-size="tablePage.pageSize"
                           background
                           :total="tablePage.total"
                           :layouts="['Home', 'PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']"
                           @page-change="handlePageChange"
                />
            </template>
        </vxe-grid>
    </div>

    <el-dialog v-model="centerDialogVisible"
               :title="dialogTitle"
               width="800"

               destroy-on-close
               align-center
               :close-on-click-modal="false"
               @close="resetFormParams"
    >
        <div class="pb-10 max-h-750 of-auto">
            <EditForm :state="state"
                      :loading="submitLoading"
                      :areaList="areaList"
                      @close="centerDialogVisible = false"
                      @submit="formSubmit"
                      @updateloading="updateloading"
            />
        </div>
    </el-dialog>
</template>
